package com.hs.srm.api.modules.othersysapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hs.srm.common.utils.R;
import com.sap.conn.jco.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.xml.XMLSerializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author socik
 * @date 2019/11/28 10:09
 * @email socik@qq.com
 */
@RestController
@RequestMapping("/api")
@Api(tags = "汇率读取接口")
public class ExchangerateGetdEatil {

    @ApiOperation(value = "汇率读取", notes = "传入IN_TAB")
    @GetMapping("/exchangerateGetdEatil/{jsonArray}")
    public R getCrmData(@ApiParam(value = "传入IN_TAB一个JSON") @PathVariable("jsonArray") String jsonArray) {
        //获取所有的json数据转化map格式
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(jsonArray);
        Map<String, Object> map = jsonObject;
        JCoDestination destination = null;
        JCoFunction function = null;
        JCoParameterList list = null;
        try {
            destination = JCoDestinationManager.getDestination("IDOC_AFS");
            function = destination.getRepository().getFunction("ZFG_CRM_EXCHANGERATE_GETDEATIL");
            list = function.getTableParameterList();
        } catch (JCoException e) {
            e.printStackTrace();
        }
        JCoTable table = list.getTable("IN_TAB");
        table.appendRow();
        map.forEach(table::setValue);
        try {
            function.execute(destination);
        } catch (JCoException e) {
            e.printStackTrace();
        }
        JCoTable returnTable = list.getTable("OUT_TAB");
        XMLSerializer xmlSerializer = new XMLSerializer();
        String  resutStr= xmlSerializer.read(returnTable.toXML()).toString();
        JSON  json=null;
        if (returnTable.getNumRows() == 1) {
              json=JSONObject.parseObject(resutStr);
        }else {
            json= JSONArray.parseArray(resutStr);
        }
        return R.ok(json);
    }
}
